package com.example.lots_of_demo.security;

import com.example.lots_of_demo.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author : LZJ
 * @description : code for LZJ
 * @date : 2021/2/11
 */
@Slf4j
@Component("MyAuthenticationSuccessHandler")
public class MyAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Value("${jwt.tokenKeyName}")
    private String tokenKeyName;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private JWTUtils jwtUtils;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String currentUser = authentication.getName();
        log.info("用户{}登录成功", currentUser);
        response.setStatus(200);
        response.setContentType("application/json;charset=UTF-8");
        HashMap<String, Object> permission = new HashMap<>(1);
        permission.put("permission", authentication.getAuthorities());
        response.setHeader(tokenKeyName, tokenHead + jwtUtils.generateToken(permission, currentUser));
        response.getWriter().append("{\"code\":0,\"msg\":\"登录成功!\",\"data\":\"success\"}");
    }
}
